using UnityEngine;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using UnityEngine.UI;

// roomIndex == -1 表示处在游戏开始的默认房间里，需要选择房间进入
namespace MyNetwork
{
    public class Launcher : MonoBehaviourPunCallbacks
    {
        public byte maxPlayersPerRoom = 2;
        /// <summary>
        /// 点击的房间序号
        /// </summary>
        public int roomIndex = -1;
        /// <summary>
        /// 当前房间序号
        /// </summary>
        public int lastRoomIndex = -1;
        public static string defaultRoomName = "Room9";
        public static byte defaultRoomMaxPlayerCount = 20;
        private void Awake()
        {
            PhotonNetwork.AutomaticallySyncScene = true;

            DontDestroyOnLoad(this);
        }
        public override void OnConnectedToMaster()
        {

            Debug.Log("已连接远程主机，即将加入默认大厅" + PhotonNetwork.IsConnectedAndReady);
            // 加入默认大厅
            // PhotonNetwork.JoinLobby();

            MainUI.Instance.ShowLevelUI();
            Debug.Log("进入默认房间");
            Debug.Log("当前客户端已加入大厅" + PhotonNetwork.NetworkClientState);
            JoinOrCreateRoom(defaultRoomName, defaultRoomMaxPlayerCount);
        }
        public override void OnDisconnected(DisconnectCause cause)
        {
            Debug.Log("已断开" + cause);
        }
        public override void OnJoinedLobby()
        {

            MainUI.Instance.ShowLevelUI();
            Debug.Log("当前客户端已加入大厅" + PhotonNetwork.NetworkClientState);
            if (!PhotonNetwork.InRoom)
            {
                Debug.Log("从大厅进入某个房间" + roomIndex + "--" + lastRoomIndex);
                if (roomIndex != lastRoomIndex)
                {
                    Debug.Log("进入其他房间" + roomIndex);
                    JoinOrCreateRoom("Room" + roomIndex, maxPlayersPerRoom);
                }
                else if (PhotonNetwork.NetworkClientState == ClientState.JoinedLobby)
                {
                    Debug.Log("进入默认房间");
                    JoinOrCreateRoom(defaultRoomName, defaultRoomMaxPlayerCount);
                }
            }
        }
        public override void OnJoinedRoom()
        {

            Debug.Log("当前客户端已加入房间:" + PhotonNetwork.CurrentRoom.ToString());
            if (roomIndex > -1)
            {
                // 更新按钮颜色
                MainUI.Instance.roomBtns[roomIndex].GetComponent<Image>().color = Color.cyan;
                // 手动更新房间人数
                MainUI.Instance.roomBtns[roomIndex].GetComponentInChildren<Text>().text = PhotonNetwork.CurrentRoom.PlayerCount + "/" + maxPlayersPerRoom;
                // 更新当前房间序号
                lastRoomIndex = roomIndex;
            }
        }
        // 离开房间时触发的回调
        public override void OnLeftRoom()
        {

            Debug.Log("已离开房间" + lastRoomIndex);

            if (lastRoomIndex == -1 && PhotonNetwork.IsConnectedAndReady)
            {
                // 从其他房间退出时，返回默认房间
                Debug.Log("强制返回默认房间");
                JoinOrCreateRoom(defaultRoomName, defaultRoomMaxPlayerCount);
                // 在游戏关卡场景中离开房间
                if (SceneManager.GetActiveScene().name != "GameMenu")
                {
                    Debug.Log("加载初始场景");
                    SceneManager.LoadSceneAsync("GameMenu");
                }
            }
        }
        // 有玩家进入房间时的回调
        public override void OnPlayerEnteredRoom(Player newPlayer)
        {
            Debug.Log(newPlayer.NickName + "进入房间");
            // 房间人满 自动开始
            if (PhotonNetwork.CurrentRoom.PlayerCount == maxPlayersPerRoom && PhotonNetwork.CurrentRoom.Name != defaultRoomName)
            {
                // 关闭选择关卡页
                MainUI.Instance.transform.GetChild(1).gameObject.SetActive(false);
                Debug.Log("房间已满人，是主客户机吗？" + PhotonNetwork.IsMasterClient);
                if (PhotonNetwork.IsMasterClient)
                {
                    Debug.Log("加载关卡场景");
                    // 加载对应关卡的场景
                    PhotonNetwork.LoadLevel(PhotonNetwork.CurrentRoom.Name);
                }
            }
        }

        public override void OnJoinRoomFailed(short returnCode, string message)
        {
            Debug.Log("加入房间失败" + message + "请重新加入..." + PhotonNetwork.InLobby + "--" + PhotonNetwork.InRoom);
        }

        public override void OnRoomListUpdate(List<RoomInfo> roomList)
        {
            Debug.Log("更新房间数:" + roomList.Count);
            // 更新房间人数信息
            foreach (RoomInfo room in roomList)
            {
                if (room.Name != defaultRoomName)
                {
                    int roomIndex = (int)(room.Name[4]) - 48;
                    Debug.Log(room.ToStringFull() + "--" + roomIndex);
                    MainUI.Instance.roomBtns[roomIndex].GetComponentInChildren<Text>().text = room.PlayerCount + "/" + maxPlayersPerRoom;
                }
            }
        }
        public void JoinOrCreateRoom(string roomName, byte maxPlayersPerRoom)
        {
            Debug.Log("JoinOrCreateRoom:正在加入房间" + PhotonNetwork.InLobby + "--" + PhotonNetwork.InRoom);
            PhotonNetwork.JoinOrCreateRoom(roomName, new RoomOptions { MaxPlayers = maxPlayersPerRoom, IsVisible = true, IsOpen = true }, default);
        }
        public void LeaveRoom()
        {
            Debug.Log("LeaveRoom:正在离开房间");
            if (SceneManager.GetActiveScene().name == "GameMenu")
            {
                // 更新按钮颜色和房间人数
                if (lastRoomIndex > -1)
                {
                    MainUI.Instance.roomBtns[lastRoomIndex].GetComponent<Image>().color = Color.white;
                    MainUI.Instance.roomBtns[lastRoomIndex].GetComponentInChildren<Text>().text = (PhotonNetwork.CurrentRoom.PlayerCount - 1) + "/" + maxPlayersPerRoom;
                }
            }
            else
            {
                Debug.Log("从关卡中退出房间");
                // 卸载关卡场景
                SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene());
                roomIndex = -1;
            }
            lastRoomIndex = -1;
            // 离开房间
            PhotonNetwork.LeaveRoom();
        }

        private void Start()
        {
            Debug.Log("监听场景加载事件");
            UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
        }
        public override void OnDisable()
        {
            base.OnDisable();
            UnityEngine.SceneManagement.SceneManager.sceneLoaded -= OnSceneLoaded;
        }
        // 场景加载完后，生成迷宫地图和玩家
        void OnSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode)
        {
            Debug.Log("呼叫关卡场景加载完成的事件" + scene.buildIndex);
            this.CallOnSceneLoaded();
        }
        public void CallOnSceneLoaded()
        {
            Debug.Log("创建迷宫地图");
            // 测试
            if (MapUI.Instance != null)
            {
                // 初始化游戏
                Debug.Log("初始化游戏");
                GameManager.Instance.CreateLevel(lastRoomIndex + 1);
                // 为离开房间按钮绑定事件
                MapUI.Instance.leaveBtn.onClick.AddListener(LeaveRoom);
            }
        }
    }
}
